<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :xl="24" :lg="24" :md="24" :sm="24" style="margin-bottom: 24px">
            <a-button type="primary" @click="todayQuery" style="margin-right: 8px">{{ $t('今日生日') }}</a-button>
            <a-button type="primary" @click="weekQuery" style="margin-right: 8px">{{ $t('近一周生日') }}</a-button>
            <a-button type="primary" @click="monthQuery" style="margin-right: 8px">{{ $t('近一月生日') }}</a-button>
            <span>{{ $t('会员生日') }}:</span>
            <a-select style="width: 90px; vertical-align: bottom; margin-left: 10px" v-model="beg_month">
              <a-select-option
                v-for="(item, index) in monthList"
                :key="index"
                :value="item"
                @click="changeMon(item, 1)"
                >{{ item }}</a-select-option
              >
            </a-select>
            <a-select style="width: 90px; vertical-align: bottom" v-model="beg_day">
              <a-select-option
                v-for="(item, index) in begDayList"
                :key="index"
                :value="item"
                @click="changeDay(item, 1)"
                >{{ item }}</a-select-option
              > </a-select
            ><span>~</span>
            <a-select style="width: 90px; vertical-align: bottom" v-model="end_month">
              <a-select-option
                v-for="(item, index) in monthList"
                :key="index"
                :value="item"
                @click="changeMon(item, 2)"
                >{{ item }}</a-select-option
              >
            </a-select>
            <a-select style="width: 90px; vertical-align: bottom" v-model="end_day">
              <a-select-option
                v-for="(item, index) in endDayList"
                :key="index"
                :value="item"
                @click="changeDay(item, 2)"
                >{{ item }}</a-select-option
              >
            </a-select>
            <a-button type="primary" @click="searchQuery" icon="search" style="margin-left: 8px">{{
              $t('查询')
            }}</a-button>
            <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">{{
              $t('重置')
            }}</a-button>
            <a @click="handleToggleSearch" style="margin-left: 8px">
              {{ toggleSearchStatus ? $t('收起') : $t('展开') }}
              <a-icon :type="toggleSearchStatus ? 'up' : 'down'" />
            </a>
            <a-button
              type="primary"
              icon="download"
              :loading="exloading"
              @click="handleExportXls($t('生日提醒'))"
              style="float: right"
              v-has="'BisMemberInfoController:export'"
              >{{ $t('导出') }}</a-button
            >
            <a-button
              type="primary"
              @click="prepareSMS"
              v-if="selectedRowKeys.length > 0"
              style="float: right; margin-right: 8px"
              v-has="'BisSmsRecordController:send'"
              >{{ $t('发送短信') }}</a-button
            >
            <a-button
              type="primary"
              @click="prepareCoupon"
              v-if="selectedRowKeys.length > 0"
              style="float: right; margin-right: 8px"
              v-has="'BisManualCouponRecordController:send'"
              >{{ $t('发送优惠券') }}</a-button
            >
          </a-col>
        </a-row>
        <template v-if="toggleSearchStatus">
          <a-row :gutter="24">
            <a-col :xl="5" :lg="5" :md="6" :sm="24">
              <a-form-item :label="$t('会员性别')">
                <a-select v-model="queryParam.sex">
                  <a-select-option v-for="(item, index) in sexList" :key="index" :value="item.value">
                    {{ item.title }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :xl="5" :lg="6" :md="7" :sm="24">
              <a-form-item :label="$t('会员类型')">
                <a-select v-model="queryParam.memberType">
                  <a-select-option v-for="(item, index) in memberTypeList" :key="index" :value="item.value">
                    {{ item.title }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :xl="5" :lg="5" :md="6" :sm="24">
              <a-form-item :label="$t('账户来源')">
                <a-select v-model="queryParam.source">
                  <a-select-option v-for="(item, index) in memberSoure" :key="index" :value="item.value">
                    {{ item.title }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :xl="5" :lg="5" :md="6" :sm="24">
              <a-form-item :label="$t('注册渠道')">
                <a-select v-model="queryParam.channel">
                  <a-select-option v-for="(item, index) in channelList" :key="index" :value="item.value">
                    {{ item.title }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="24">
            <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item :label="$t('钱包类型')">
                <a-select style="width: 90px" v-model="queryParam.accountType">
                  <a-select-option value="coin">{{ $t('代币') }}</a-select-option>
                  <a-select-option value="integral">{{ $t('积分') }}</a-select-option>
                  <a-select-option value="lottery">{{ $t('彩票') }}</a-select-option>
                  <a-select-option value="alottery">{{ $t('A票') }}</a-select-option>
                  <a-select-option value="points">{{ $t('A币') }}</a-select-option>
                </a-select>
                <a-input
                  style="width: 80px; margin-left: 6px; margin-right: 2px"
                  v-model="queryParam.accountTypeBeg"
                />~
                <a-input style="width: 80px" v-model="queryParam.accountTypeEnd" />
              </a-form-item>
            </a-col>
            <a-col :xl="10" :lg="11" :md="12" :sm="24">
              <a-form-item :label="$t('注册时间')">
                <j-date
                  :show-time="{ defaultValue: moment('00:00:00', 'HH:mm:ss') }"
                  valueFormat="YYYY-MM-DD HH:mm:ss"
                  dateFormat="YYYY-MM-DD HH:mm:ss"
                  :placeholder="$t('请选择开始时间')"
                  class="query-group-cust"
                  v-model="queryParam.regTimeBeg"
                ></j-date>
                <span class="query-group-split-cust"></span>
                <j-date
                  :show-time="{ defaultValue: moment('23:59:59', 'HH:mm:ss') }"
                  valueFormat="YYYY-MM-DD HH:mm:ss"
                  dateFormat="YYYY-MM-DD HH:mm:ss"
                  :placeholder="$t('请选择结束时间')"
                  class="query-group-cust"
                  v-model="queryParam.regTimeEnd"
                ></j-date>
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item :label="$t('会员信息')">
                <a-input
                  :placeholder="$t('请输入会员手机号/卡号/姓名/证件号/微信昵称')"
                  v-model="queryParam.memberInfo"
                ></a-input>
              </a-form-item>
            </a-col>
          </a-row>
        </template>
      </a-form>
    </div>
    <!-- 查询区域-END -->

    <!-- table区域-begin -->
    <div>
      <a-table
        ref="table"
        size="middle"
        :scroll="{ x: true }"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        class="j-table-force-nowrap"
        @change="handleTableChange"
        :rowSelection="rowSelection"
      >
        <span slot="action" slot-scope="text, record">
          <a @click="handleDetail(record)">{{ $t('详情') }}</a>
          <a @click="resetPassword(record)" v-if="record.memberAccount.state == 0" style="margin-left: 8px">{{
            $t('重置密码')
          }}</a>
          <a @click="editAccount(record)" v-if="record.memberAccount.state == 0" style="margin-left: 8px">{{
            $t('账户修正')
          }}</a>
          <a @click="handleLoss(record)" v-if="record.memberAccount.state == 0" style="margin-left: 8px">{{
            $t('挂失')
          }}</a>
        </span>
      </a-table>
    </div>
    <send-coupon-modal ref="sendForm" @ok="onClearSelected"></send-coupon-modal>
    <send-sms-modal ref="sendSMS" @ok="onClearSelected"></send-sms-modal>
  </a-card>
</template>

<script>
import moment from 'moment'
import '@/assets/less/TableExpand.less'
import { mixinDevice } from '@/utils/mixin'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { initDictOptions, filterMultiDictText } from '@/components/dict/JDictSelectUtil'
import { getAction } from '@/api/manage'
import SendCouponModal from './modules/SendCouponModal'
import SendSmsModal from './modules/SendSMSModal'

export default {
  name: 'BirthdayReminder',
  mixins: [JeecgListMixin, mixinDevice],
  components: { SendCouponModal, SendSmsModal },
  data() {
    return {
      moment,
      description: '生日提醒页面',
      dictOptions: {
        memberType: [],
        memberSoure: [],
      },
      queryParam: {
        memberType: '',
        state: '',
        source: '',
        sex: '',
        channel: '',
        birthdayBeg: null,
        birthdayEnd: null,
        accountType: 'coin',
        type: '',
      },
      isorter: {
        column: 'regTime',
        order: 'desc',
      },
      beg_month: this.$t('月'),
      beg_day: this.$t('日'),
      end_month: this.$t('月'),
      end_day: this.$t('日'),
      monthList: [],
      begDayList: [],
      endDayList: [],
      // 表头
      columns: [
        {
          title: this.$t('手机号'),
          align: 'center',
          dataIndex: 'phone',
        },
        {
          title: this.$t('会员卡号'),
          align: 'center',
          dataIndex: 'memberCards',
          customRender: function (text, record) {
            if (text.length != 0) {
              return text
                .filter((a) => {
                  return a.state === '0'
                })
                .map((a) => {
                  return a.chipNo
                })
                .join(',')
            } else {
              return ''
            }
          },
        },
        {
          title: this.$t('姓名'),
          align: 'center',
          dataIndex: 'name',
        },
        {
          title: this.$t('会员类型'),
          align: 'center',
          dataIndex: 'memberAccount.memberType',
          customRender: (text) => (text ? filterMultiDictText(this.dictOptions['memberType'], text) : ''),
        },
        {
          title: this.$t('性别'),
          align: 'center',
          dataIndex: 'sex_dictText',
        },
        {
          title: this.$t('生日'),
          align: 'center',
          dataIndex: 'birthday',
          customRender: function (text) {
            return !text ? '' : text.length > 10 ? text.substr(0, 10) : text
          },
        },
        {
          title: this.$t('代币'),
          align: 'center',
          dataIndex: 'memberAccount',
          customCell: () => {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
          customRender: function (text) {
            return text ? (parseFloat(text.presentCoin) + parseFloat(text.realCoin)).toFixed(2) : ''
          },
        },
        {
          title: this.$t('彩票'),
          align: 'center',
          dataIndex: 'memberAccount.lottery',
          customCell: () => {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
          customRender: (text, r) => {
            text = text == null || text == '' || text == undefined ? 0 : parseFloat(text)
            return text.toFixed(0)
          },
        },
        {
          title: this.$t('积分'),
          align: 'center',
          dataIndex: 'memberAccount.integral',
          customCell: () => {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
          customRender: (text, r) => {
            text = text == null || text == '' || text == undefined ? 0 : parseFloat(text)
            return text.toFixed(0)
          },
        },
        {
          title: this.$t('A币'),
          align: 'center',
          dataIndex: 'memberAccount.points',
          customCell: () => {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
          customRender: (text, r) => {
            text = text == null || text == '' || text == undefined ? 0 : parseFloat(text)
            return text.toFixed(0)
          },
        },
        {
          title: this.$t('A票'),
          align: 'center',
          dataIndex: 'memberAccount.alottery',
          customCell: () => {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
          customRender: (text, r) => {
            text = text == null || text == '' || text == undefined ? 0 : parseFloat(text)
            return text.toFixed(0)
          },
        },
        {
          title: this.$t('账户来源'),
          align: 'center',
          dataIndex: 'memberAccount.source_dictText',
        },
        {
          title: this.$t('注册渠道'),
          align: 'center',
          dataIndex: 'channel_dictText',
        },
        {
          title: this.$t('注册时间'),
          align: 'center',
          dataIndex: 'regTime',
        },
      ],
      url: {
        list: '/member/bisMemberInfo/listByBirthday',
        exportXlsUrl: '/member/bisMemberInfo/exportXlsByBirthday',
        importExcelUrl: 'sys/common/upload',
      },
      memberTypeList: [], //会员类型
      sexList: [],
      channelList: [],
      memberSoure: [],
    }
  },
  created() {
    for (var i = 1; i <= 12; i++) {
      this.monthList.push(i)
    }
    for (var i = 1; i <= 31; i++) {
      this.begDayList.push(i)
      this.endDayList.push(i)
    }
  },
  computed: {
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: (selectedRowKeys, selectionRows) => {
          this.selectedRowKeys = selectedRowKeys
          this.selectionRows = selectionRows
        },
        /* getCheckboxProps: (record) => ({
          props: {
            disabled: !record.phone,
          },
        }), */
      }
    },
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    },
  },
  methods: {
    disabledYear(current) {
      // 这里可以根据需要禁用某些年份
      return false
    },
    // 处理面板变化
    handlePanelChange(value, mode) {
      if (mode === 'year') {
        // 阻止切换到年份选择面板
        return
      }
    },
    initDictConfig() {
      let dictCode = 'bis_member_rule,name,id'
      getAction(`/sys/dict/getDictItems/${dictCode}`, {}).then((res) => {
        if (res.success) {
          this.$set(this.dictOptions, 'memberType', res.result)
          this.memberTypeList = res.result
          this.memberTypeList.unshift({ title: this.$t('全部'), value: '' })
        }
      })
      initDictOptions('bis_member.sex').then((res) => {
        if (res.success) {
          this.sexList = res.result
          this.sexList.unshift({ title: this.$t('全部'), value: '' })
        }
      })
      initDictOptions('bis_device_info.type').then((res) => {
        if (res.success) {
          this.channelList = res.result
          this.channelList.unshift({ title: this.$t('全部'), value: '' })
        }
      })
      initDictOptions('bis_member_infor.source').then((res) => {
        if (res.success) {
          this.$set(this.dictOptions, 'memberSoure', res.result)
          this.memberSoure = res.result
          this.memberSoure.unshift({ title: this.$t('全部'), value: '' })
        }
      })
    },
    changeMon(month, state) {
      month = parseInt(month, 10)
      let year = new Date().getFullYear()
      var temp = new Date(year, month, 0)
      let n = +temp.getDate()
      let dataTimes = []
      for (var i = 1; i < n + 1; i++) {
        dataTimes.push(i)
      }
      if (state == 1) {
        this.begDayList = dataTimes
        this.beg_month = month
        if (this.beg_day == this.$t('日')) {
          this.beg_day = dataTimes[0]
        }
        if (month < 10) {
          if (this.beg_day < 10) {
            this.queryParam.birthdayBeg = '0' + this.beg_month + '-0' + this.beg_day
          } else {
            this.queryParam.birthdayBeg = '0' + this.beg_month + '-' + this.beg_day
          }
        } else {
          if (this.beg_day < 10) {
            this.queryParam.birthdayBeg = this.beg_month + '-0' + this.beg_day
          } else {
            this.queryParam.birthdayBeg = this.beg_month + '-' + this.beg_day
          }
        }
      } else {
        this.endDayList = dataTimes
        this.end_month = month
        if (this.end_day == this.$t('日')) {
          this.end_day = dataTimes[dataTimes.length - 1]
        }
        if (month < 10) {
          if (this.end_day < 10) {
            this.queryParam.birthdayEnd = '0' + this.end_month + '-0' + this.end_day
          } else {
            this.queryParam.birthdayEnd = '0' + this.end_month + '-' + this.end_day
          }
        } else {
          if (this.end_day < 10) {
            this.queryParam.birthdayEnd = this.end_month + '-0' + this.end_day
          } else {
            this.queryParam.birthdayEnd = this.end_month + '-' + this.end_day
          }
        }
      }
    },
    changeDay(day, state) {
      if (state == 1) {
        this.beg_day = day
        if (day < 10) {
          if (this.beg_month < 10) {
            this.queryParam.birthdayEnd = '0' + this.beg_month + '-0' + this.beg_day
          } else {
            this.queryParam.birthdayEnd = this.beg_month + '-0' + this.beg_day
          }
        } else {
          if (this.beg_month < 10) {
            this.queryParam.birthdayEnd = '0' + this.beg_month + '-' + this.beg_day
          } else {
            this.queryParam.birthdayEnd = this.beg_month + '-' + this.beg_day
          }
        }
      } else {
        this.end_day = day
        if (day < 10) {
          if (this.end_month < 10) {
            this.queryParam.birthdayEnd = '0' + this.end_month + '-0' + this.end_day
          } else {
            this.queryParam.birthdayEnd = this.end_month + '-0' + this.end_day
          }
        } else {
          if (this.end_month < 10) {
            this.queryParam.birthdayEnd = '0' + this.end_month + '-' + this.end_day
          } else {
            this.queryParam.birthdayEnd = this.end_month + '-' + this.end_day
          }
        }
      }
    },
    searchReset() {
      this.queryParam = {
        memberType: '',
        state: '',
        source: '',
        sex: '',
        channel: '',
        birthdayBeg: '',
        birthdayEnd: '',
        accountType: 'coin',
        type: '',
      }
      this.beg_month = this.$t('月')
      this.beg_day = this.$t('日')
      this.end_month = this.$t('月')
      this.end_day = this.$t('日')
      this.searchQuery(1)
    },
    todayQuery() {
      this.queryParam.birthdayBeg = moment().format('MM-DD')
      this.queryParam.birthdayEnd = moment().format('MM-DD')
      this.searchQuery(1)
    },
    weekQuery() {
      this.queryParam.birthdayBeg = moment().subtract('days', 6).format('MM-DD')
      this.queryParam.birthdayEnd = moment().format('MM-DD')
      this.searchQuery(1)
    },
    monthQuery() {
      this.queryParam.birthdayBeg = moment().subtract('days', 29).format('MM-DD')
      this.queryParam.birthdayEnd = moment().format('MM-DD')
      this.searchQuery(1)
    },
    prepareSMS() {
      let that = this
      getAction('/bis/bisSysParameter/queryByName', { name: 'shumiAccountId' }).then((res0) => {
        if (res0.success && res0.result.svalue == '400637') {
          that.$message.warning(
            that.$t('请先联系数米公司开通短信账户；联系方式：程女士，电话18611733312 或 微信号 Cgm_jiayou')
          )
          return
        }
        if (res0.success && res0.result.svalue != '400637') {
          let arr = that.selectionRows
            .filter((row) => {
              return row.phone != ''
            })
            .map((row) => {
              row.memberCardNo = ''
              row.totalCoin = (row.memberAccount.realCoin + row.memberAccount.presentCoin).toFixed(2)
              if (row.memberCards && row.memberCards.length > 0) {
                row.memberCardNo = row.memberCards.filter((m) => {
                  return m.state == 0
                })[0].chipNo
              }
              let dtl = {
                memberId: row.id,
                memberCardNo: row.memberCardNo,
                phone: row.phone,
                totalCoin: row.totalCoin,
                name: row.name,
              }
              return dtl
            })
          if (arr.length == 0) {
            that.$message.warning(that.$t('至少选择一位有手机号的会员'))
            return
          }
          that.$refs.sendSMS.edit(arr)
        }
      })
    },
    prepareCoupon() {
      let arr = this.selectionRows.map((row) => {
        row.memberCardNo = ''
        row.totalCoin = (row.memberAccount.realCoin + row.memberAccount.presentCoin).toFixed(2)
        if (row.memberCards && row.memberCards.length > 0) {
          row.memberCardNo = row.memberCards.filter((m) => {
            return m.state == 0
          })[0].chipNo
        }
        let dtl = {
          memberId: row.id,
          memberCardNo: row.memberCardNo,
          phone: row.phone,
          totalCoin: row.totalCoin,
          name: row.name,
        }
        return dtl
      })
      this.$refs.sendForm.edit(arr)
    },
  },
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>